33C - Wonderful Randomized Sum - CodeForces Solution


greedy *1800

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
using namespace std;



int main(){
	
	int n;
	cin>>n;

	int arr[n];
	

	int VACSuffix[n];
	int MVASuffix[n];

	int VACPrefix[n];
	int MVAPrefix[n];

	int val;
	cin>>val;
	arr[0] = val;
	VACPrefix[0] = val;
	if(val<0){
		MVAPrefix[0] = val;
	}
	else {
		MVAPrefix[0] = 0;
	}

	for (int i = 1; i < n; ++i)
	{
		int val;
		cin>>val;
		arr[i]=val;
		VACPrefix[i] = VACPrefix[i-1]+val;
		if(MVAPrefix[i-1] > VACPrefix[i]){
			MVAPrefix[i] = VACPrefix[i];
		}
		else{
			MVAPrefix[i] = MVAPrefix[i-1];
		}
	}

	if(n==2){
		int result = abs(arr[0])+abs(arr[1]);
		cout<<result<<endl;
		return 0;
	}

	VACSuffix[n-1] = arr[n-1];
	if(arr[n-1]<0){
		MVASuffix[n-1] = arr[n-1];
	}
	else{
		MVASuffix[n-1] = 0;
	}
	
	for (int i = n-2; i >=0 ; --i)
	{
		VACSuffix[i] = VACSuffix[i+1]+arr[i];
		if(MVASuffix[i+1] > VACSuffix[i]){
			MVASuffix[i] = VACSuffix[i];
		}
		else{
			MVASuffix[i] = MVASuffix[i+1];
		}
	}
	int maxSum = 0;
	for (int i = 0; i < n-1; ++i)
	{
		if(maxSum > MVASuffix[i+1]+MVAPrefix[i]){
			maxSum =  MVASuffix[i+1]+MVAPrefix[i];
		}
	}
	int maxVal = VACPrefix[n-1];
	maxVal = max(maxVal,-VACPrefix[n-1]);
	maxVal = max(maxVal, VACPrefix[n-1]-2* maxSum);

	cout<<maxVal<<endl;
	return 0;
}
    				 	      	 	 				 	   		


Comments

Submit
0 Comments
More Questions

462A - Appleman and Easy Task
839C - Journey
622A - Infinite Sequence
659C - Tanya and Toys
1266A - Competitive Programmer
234C - Weather
1332C - K-Complete Word
525C - Ilya and Sticks
1555C - Coin Rows
1324C - Frog Jumps
715A - Plus and Square Root
774D - Lie or Truth
1186D - Vus the Cossack and Numbers
505B - Mr Kitayuta's Colorful Graph
1324D - Pair of Topics
157B - Trace
34C - Page Numbers
279A - Point on Spiral
1294D - MEX maximizing
447A - DZY Loves Hash
23B - Party
63D - Dividing Island
1203E - Boxers
1547F - Array Stabilization (GCD version)
358A - Dima and Continuous Line
1385C - Make It Good
651A - Joysticks
1474D - Cleaning
1588A - Two Arrays
816A - Karen and Morning